import { Button, Card, Checkbox, Form, Input, List, Modal } from "antd"
import { useEffect, useState } from "react"
import { openDialog } from "@linksaas-minapp/api/min_app_fs"
import { FolderOpenOutlined, PlusOutlined } from "@ant-design/icons"
import { v4 as uuidv4 } from 'uuid'
import { genResultFile } from "@linksaas-minapp/grpc-proxy-api"
import type { GrpcServerInfo } from "@linksaas-minapp/api/extra_info"
import { getMinAppInfo } from "@linksaas-minapp/api"

interface ImportPath {
    id: string;
    path: string;
}

export interface OpenModalProps {
    onCancel: () => void;
    onOk: (newGrpcApiId: string, grpcInfo: GrpcServerInfo) => void;
}

function OpenModal(props: OpenModalProps) {
    const [rootPath, setRootPath] = useState("");
    const [importPathList, setImportPathList] = useState([] as ImportPath[]);
    const [remoteAddr, setRemoteAddr] = useState("");
    const [secure, setSecure] = useState(false);

    const choiceRootPath = async () => {
        const path = await openDialog("选择grpc接口定义路径", true);
        if (path != "") {
            setRootPath(path);
        }
    };

    const choiceImportPath = async (id: string) => {
        const path = await openDialog("选择导入路径", true);
        if (path == "") {
            return;
        }
        const tmpList = importPathList.slice();
        const index = tmpList.findIndex(item => item.id == id);
        if (index != -1) {
            tmpList[index].path = path;
            setImportPathList(tmpList);
        }
    };

    const parseGrpc = async () => {
        const newGrpcApiId = uuidv4();
        await genResultFile(newGrpcApiId, rootPath, importPathList.filter(item => item.path != "").map(item => item.path));
        props.onOk(newGrpcApiId, {
            addr: remoteAddr,
            rootPath: rootPath,
            importPathList: importPathList.map(item => item.path),
            secure: secure,
        });
    };

    useEffect(() => {
        const minAppInfo = getMinAppInfo();
        if (minAppInfo == undefined) {
            return;
        }
        if (minAppInfo.extraInfo != undefined && minAppInfo.extraInfo.length > 0) {
            const obj = JSON.parse(minAppInfo.extraInfo) as GrpcServerInfo;
            setRootPath(obj.rootPath ?? "");
            setImportPathList((obj.importPathList ?? []).map(path => ({
                id: uuidv4(),
                path: path,
            })));
            setRemoteAddr(obj.addr ?? "");
            setSecure(obj.secure ?? false);
        }
    }, []);

    return (
        <Modal open title="打开grpc接口定义"
            okText="打开" okButtonProps={{ disabled: rootPath == "" || remoteAddr.includes(":") == false }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                parseGrpc();
            }}>
            <div style={{ maxHeight: "calc(100vh - 300px)", overflowY: "auto" }}>
                <Form>
                    <Form.Item label="grpc路径">
                        <Input value={rootPath} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setRootPath(e.target.value.trim());
                        }} addonAfter={<Button type="text" icon={<FolderOpenOutlined />} style={{ height: "20px", minWidth: 0, padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                choiceRootPath();
                            }} />} />
                    </Form.Item>
                    <Form.Item label="远程地址" help={
                        <>
                            {remoteAddr.includes(":") == false && (
                                <span style={{ color: "red" }}>输入格式[host]:[port]</span>
                            )}
                        </>
                    }>
                        <Input value={remoteAddr} onChange={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setRemoteAddr(e.target.value.trim());
                        }} />
                    </Form.Item>
                    <Form.Item label="tls加密">
                        <Checkbox checked={secure} onChange={e => {
                            e.stopPropagation();
                            setSecure(e.target.checked);
                        }} />
                    </Form.Item>
                </Form>
                <Card title="导入路径" headStyle={{ padding: "0px 0px" }} bodyStyle={{ padding: "0px 0px" }} bordered={false}
                    extra={
                        <Button type="link" icon={<PlusOutlined />} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            const tmpList = importPathList.slice();
                            tmpList.push({
                                id: uuidv4(),
                                path: "",
                            });
                            setImportPathList(tmpList);
                        }} />
                    }>
                    <List rowKey="id" dataSource={importPathList} renderItem={(item) => (
                        <List.Item extra={
                            <Button type="link" onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                const tmpList = importPathList.filter(cmpItem => cmpItem.id != item.id);
                                setImportPathList(tmpList);
                            }}>移除</Button>
                        }>
                            <Input value={rootPath} onChange={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                const tmpList = importPathList.slice();
                                const index = tmpList.findIndex(cmpItem => cmpItem.id == item.id);
                                if (index != -1) {
                                    tmpList[index].path = e.target.value.trim();
                                    setImportPathList(tmpList);
                                }
                            }} addonAfter={<Button type="text" icon={<FolderOpenOutlined />} style={{ height: "20px", minWidth: 0, padding: "0px 0px" }}
                                onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    choiceImportPath(item.id);
                                }} />} />
                        </List.Item>
                    )} />
                </Card>
            </div>
        </Modal>
    )
}

export default OpenModal